package com.foreveross.law.controller.user;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.foreveross.law.commons.StringUtils;

@Controller
public class UserController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@RequestMapping(value="/user/tologin")
	public String loginPage(){
		return "/user/login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(String username,String password,HttpServletRequest request){
		//获取验证码
				logger.info("登录....");
				if (StringUtils.isNull(username) || StringUtils.isNull(password)) {
					request.setAttribute("error", "用户名或密码不能为空！");
					return loginPage();
				}
				
				
				
				// 想要得到 SecurityUtils.getSubject()　的对象．．访问地址必须跟ｓｈｉｒｏ的拦截地址内．不然后会报空指针
				Subject user = SecurityUtils.getSubject();
				// 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
				// 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
				// 当以上认证成功后会向下执行,认证失败会抛出异常
				UsernamePasswordToken token = new UsernamePasswordToken("sysadmin", "123456");
				try {
					user.login(token);
				} catch (LockedAccountException lae) {
					token.clear();
					request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
					return loginPage();
				} catch (ExcessiveAttemptsException e) {
					token.clear();
					request.setAttribute("error", "账号：" + username + " 登录失败次数过多,锁定10分钟!");
					return loginPage();
				} catch (AuthenticationException e) {
					token.clear();
					request.setAttribute("error", "用户或密码不正确！");
					return loginPage();
				}
				return "redirect:/hello";
	}
	
}
